package com.yjc.drygoods.member.service.impl;

import com.yjc.common.vo.MemberRespVo;
import com.yjc.drygoods.member.dao.MemberReceiveAddressDao;
import com.yjc.drygoods.member.entity.MemberReceiveAddressEntity;
import com.yjc.drygoods.member.interceptor.LoginUserInterceptor;
import com.yjc.drygoods.member.vo.FareVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.Query;

import com.yjc.drygoods.member.service.MemberReceiveAddressService;
import org.springframework.util.StringUtils;


@Service("memberReceiveAddressService")
public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressDao, MemberReceiveAddressEntity> implements MemberReceiveAddressService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberReceiveAddressEntity> page = this.page(
                new Query<MemberReceiveAddressEntity>().getPage(params),
                new QueryWrapper<MemberReceiveAddressEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<MemberReceiveAddressEntity> getMemberAddress(Long memberId) {

        return this.list(new QueryWrapper<MemberReceiveAddressEntity>().eq("member_id", memberId));
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo fare = new FareVo();
        MemberReceiveAddressEntity memberAddrInfo = this.getById(addrId);
        if (memberAddrInfo != null) {
            fare.setAddress(memberAddrInfo);
            String phone = memberAddrInfo.getPhone();
            if (!StringUtils.isEmpty(phone)) {
                //取手机号最后一位，模拟该收货地址的运费
                String substring = phone.substring(phone.length() - 1, phone.length());
                fare.setFare(new BigDecimal(substring));
            }
            return fare;
        }
        return null;
    }

    @Override
    public void updateDefaultAddress(Long addressId) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        Long memberId = memberRespVo.getId();
        //1.更改当前用户的当前id地址为默认地址
        this.baseMapper.updateCurrentIdDefaultAddress(addressId, memberId);
        //2.将当前用户的其他地址全部置为非默认地址
        this.baseMapper.updateOtherAddressNotDefault(addressId, memberId);
    }

    @Override
    public void deleteAddressAndKeepDefault(Long addressId) {
        //1.删除地址
        this.removeById(addressId);

    }

}